<template>
    <div class="content">
        <div class="pageSearchView">
            <SearchForm v-model="searchParam" :fields="searchFields" :handleSearch="handleSearch" />
        </div>

        <div class="pageTableView">
            <div class="pageTableMenuView">
                <div class="pageTableTitle">
                    列表信息
                    <el-icon>
                        <house-icon />
                    </el-icon>
                </div>
                <div class="pageTableButView">
                    <el-button :icon="Plus" @click="handleAdd">新建</el-button>

                </div>
            </div>
            <!-- 表格 -->
            <el-table class="pageTableClass" :data="taskNoPage" height="calc(100vh - 280px)" :loading="isLoading"
                row-key="id">


                <el-table-column label="序号" align="center" width="70">
                    <template #default="scope">
                        {{ (paginationParams.current - 1) * paginationParams.pageSize + scope.$index + 1 }}
                    </template>
                </el-table-column>
                <el-table-column prop="name" min-width="150" label="故障名称" align="center">
                    <template #default="scope">
                        <span>{{ scope.row.name }}</span>
                        <span v-for="n in scope.row.levelNo" :key="n">—</span>
                    </template>
                </el-table-column>

                <el-table-column label="操作" fixed="right" width="300">
                    <template #default="scope">
                        <el-button @click="handleEdit(scope.row, 'son')" text size="small" plain
                            :icon="Film">新建子级</el-button>
                        <el-button @click="handleEdit(scope.row)" size="small" plain text :icon="Edit">编辑</el-button>
                        <el-button @click="handleDelete(scope.row)" size="small" type="danger" plain text
                            :icon="Delete">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

        </div>

        <!-- 新建/编辑弹框 -->
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="60%">

            <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
                <el-form-item label="故障名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入故障名称"></el-input>
                </el-form-item>

            </el-form>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleSubmit">确定</el-button>
                </span>
            </template>
        </el-dialog>

    </div>
</template>

<script setup>
import SearchForm from '@/components/SearchForm.vue';
import { useToolData } from '@/hooks/baseData/tooling';
import axiosInstance from "@/utils/http/api";
import { Delete, Edit, Plus, Film } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { computed, onMounted, ref } from 'vue';

import { maintenanceMalfunctionPage, maintenanceMalfunctionUpdate, maintenanceMalfunctionAdd, maintenanceMalfunctionDel } from '@/api/device/faultType';

const activeName = ref('CREATED')
const searchParam = ref({})
const searchFields = ref([
    {
        name: "name",
        label: "故障名称",
        component: "input",
        placeholder: "",
        class: "!w-[350px]",
    },
])

const pageTotal = ref(0)
const taskNoPage = ref([])
const paginationParams = ref({ pageSize: 10, current: 1 })
const dialogVisible = ref(false);
const dialogTitle = ref('新建');
const form = ref({});
const selectedRows = ref([]);
const rules = ref({
    name: [{ required: true, message: '请输入名字', trigger: 'blur' }]
});
const parentID = ref(null);
const levelNo = ref(null);

onMounted(() => {
    fetchPage()
});

const handleAdd = () => {
    form.value = {};
    parentID.value = null; // 清空父ID
    levelNo.value = null; // 清空层级
    dialogTitle.value = '新建';
    dialogVisible.value = true;
};

const handleEdit = (row, type) => {
    if (type === 'son') {
        dialogTitle.value = '新建子级';
        parentID.value = row.id;
        form.value = { id: undefined };
    } else {
        form.value = { ...row };
        parentID.value = row.parentId; // 设置父ID
        levelNo.value = row.levelNo; // 设置层级
        dialogTitle.value = '编辑';

    }
    dialogVisible.value = true;
};
const transformToTree = (data) => {
    const map = new Map();
    const tree = [];

    data.forEach(item => {
        map.set(item.id, { ...item, children: [] });
    });

    data.forEach(item => {
        if (item.parentId === "0") {
            tree.push(map.get(item.id));
        } else {
            const parent = map.get(item.parentId);
            if (parent) {
                parent.children.push(map.get(item.id));
            }
        }
    });

    return tree;
}
const handleSubmit = () => {
    const api = ['新建', '新建子级'].includes(dialogTitle.value) ? maintenanceMalfunctionAdd : maintenanceMalfunctionUpdate;

    // 如果是新建，则将父ID和层级设置到表单中
    if (['新建', '新建子级'].includes(dialogTitle.value)) {
        form.value.parentId = parentID.value;
        form.value.levelNo = levelNo.value;
        form.value.type = 2;
    }

    api(form.value).then(res => {
        if (res.code === 200) {
            ElMessage.success(dialogTitle.value === '新建' ? '新建成功' : '编辑成功');
            dialogVisible.value = false;
            fetchPage();
        } else {
            ElMessage.error(res.message);
        }
    });
};

const handleDelete = (row) => {
    ElMessageBox.confirm('确认删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        maintenanceMalfunctionDel({ ids: [row.id] }).then(res => {
            if (res.code === 200) {
                ElMessage.success('删除成功');
                fetchPage();
            } else {
                ElMessage.error(res.message);
            }
        });
    }).catch(() => { });
};

const handleDeleteSelected = () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请至少选择一条记录');
        return;
    }

    ElMessageBox.confirm('确认批量删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        const ids = selectedRows.value.map(row => row.id);
        maintenanceMalfunctionDel(ids).then(res => {
            if (res.code === 200) {
                ElMessage.success('批量删除成功');
                fetchPage();
            } else {
                ElMessage.error(res.message);
            }
        });
    }).catch(() => { });
};

const handleSelectionChange = (rows) => {
    selectedRows.value = rows;
};

const fetchPage = (params) => {
    maintenanceMalfunctionPage({
        ...searchParam.value,
        type:2,
    }).then(res => {
        taskNoPage.value = transformToTree(res.data.records);
        console.log(transformToTree(res.data.records))
        pageTotal.value = res.data.total;
    });
};

const handleSearch = () => {
    fetchPage();
};




</script>

<style scoped>
/* 样式可以根据需要进行调整 */
</style>